package com.fpf.lab01_basics;

/**
 * 死锁
 * 线程A持有锁A，睡醒后尝试获取锁B，等待B释放锁
 * 线程B持有锁B，睡醒后尝试获取锁A，等待A释放锁
 * 循环等待造成死锁
 */
public class Demo10_DeadLock {
    private static final Object lockA = new Object();
    private static final Object lockB = new Object();

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            synchronized (lockA) {
                sleep();
                synchronized (lockB) {
                    System.out.println("t1 got both locks");
                }
            }
        }, "Thread-A");
        Thread t2 = new Thread(() -> {
            synchronized (lockB) {
                sleep();
                synchronized (lockA) {
                    System.out.println("t2 got both locks");
                }
            }
        }, "Thread-B");
        t1.start();
        t2.start();
    }

    private static void sleep() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException ignored) {
        }
    }

}
